const Base = require('./base.js');
module.exports = class extends Base {

	async bindUser(user, userInfo) {
		console.log(userInfo);

		userInfo.nickname = think.emojiFilter(userInfo.nickname);
		let create_time = new Date().valueOf();
		userInfo.create_time = create_time;
		await this.transaction(async() => {

			const userid = await think.model("system/user").db(this.db()).add({
				username: userInfo.wxid,
				status: 1,
				create_time: create_time,
				nickname: userInfo.nickname
			});

			await think.model("system/asset").db(this.db()).add({
				score: 0,
				amount: 0,
				rebate: 0,
				team_count: 0,
				user_id: userid,
				agency_id: user.agency_id,
				create_time: create_time,
			});
			if(!think.isEmpty(user.agency_id)) {
				let agencyUserId = await think.model("system/agency").db(this.db()).where({
					id: user.agency_id
				}).getField("user_id", true);
				await think.model("system/asset").db(this.db()).where({
					user_id: agencyUserId
				}).increment("team_count");
				//根据推荐人数自动升级
				let agencyAsset = await think.model("system/asset").db(this.db()).where({
					user_id: agencyUserId
				}).find();
				if(agencyAsset.team_count >= think.config("setup.vipMemberCondition") && agencyAsset.level == 1) {
					await think.model("system/asset").db(this.db()).where({
						user_id: agencyUserId
					}).update({
						level: 2
					});
					await think.model("system/user").db(this.db()).where({
						id: agencyUserId
					}).update({
						level: 2
					});
				}
			}
			await think.model("system/agency").db(this.db()).add({
				level: 1,
				status: 1,
				user_id: userid,
				create_time: create_time,
			});
			userInfo.user_id = userid;

			if(think.isEmpty(user.id)) {
				return await this.add(userInfo);
			} else {
				return await this.where({
					id: user.id
				}).update(userInfo);
			}

		});

	}

};